package com.china.produce.pdf;

import org.apache.fontbox.ttf.TTFParser;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.encoding.Encoding;
import org.apache.pdfbox.pdmodel.font.encoding.MacOSRomanEncoding;
import org.apache.pdfbox.pdmodel.font.encoding.WinAnsiEncoding;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/11/4
 */
public class PdfBox {

    public static void main(String[] args) throws IOException {
        String wordFilePath = "/Users/niujie/Desktop/牛杰-Java研发工程师.docx"; // 输入 Word 文件路径
        String pdfFilePath = "/Users/niujie/Desktop/牛杰.pdf";    // 输出 PDF 文件路径

        try (XWPFDocument doc = new XWPFDocument(new FileInputStream(wordFilePath));
             PDDocument pdfDoc = new PDDocument()) {

            PDPage pdfPage = new PDPage();
            pdfDoc.addPage(pdfPage);
            PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, pdfPage);
            PDType0Font customFonts = PDType0Font.load(pdfDoc, new File("/Users/niujie/Downloads/09_NotoSerifCJKsc/OTF/SimplifiedChinese/NotoSerifCJKsc-Black.otf"));

            for (XWPFParagraph paragraph : doc.getParagraphs()) {
                String text = paragraph.getText();

                contentStream.beginText();
                contentStream.setFont(customFonts, 12);
                contentStream.newLineAtOffset(100, 700); // 设置文本起始位置
                contentStream.showText(text);
                contentStream.endText();
            }
            contentStream.close();

            pdfDoc.save(pdfFilePath);
            System.out.println("Converted Word to PDF!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
